package com.example.music_mediaplayer.service;


import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;

import com.example.music_mediaplayer.MainActivity;
import com.example.music_mediaplayer.PlayingActivity;
import com.example.music_mediaplayer.api.ILrcBuilder;
import com.example.music_mediaplayer.control.DefaultLrcBuilder;
import com.example.music_mediaplayer.globalvariable.GlobalVariable;

import com.example.music_mediaplayer.model.LrcContent;
import com.example.music_mediaplayer.model.LrcRow;
import com.example.music_mediaplayer.model.MessageEvent;
import com.example.music_mediaplayer.model.SongsInfomation;
import com.example.music_mediaplayer.observermodel.MyObservable;
import com.example.music_mediaplayer.tool.LogoutT;
import com.example.music_mediaplayer.tool.SharePreferenceTools;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by quan on 2018/1/6.
 */

public class MyService  extends Service {
    public static MediaPlayer mediaPlayer = new MediaPlayer();
    private int current = 0;//当前播放的音乐
    public static String playState = "1";//播放类型
    private int currentTime;//当前播放长度
    private int duration;//播放长度
    private Intent intent;
    public static int number;
    private static String songLrc;
    private  String msg;
    private Timer timer = new Timer();
    TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            getMusicCurrentPosition();
//            MyObservable.getInstance().notifyChangeView(number);
        }
    };

    public static Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    Bundle bundle = msg.getData();
                    if (bundle.get("state").equals("1")){
                        playState = "1";
                    }else if (bundle.get("state").equals("2")){
                        playState = "2";
                    }else if (bundle.get("state").equals("3")){
                        playState = "3";
                    }
                    break;
                case 2:
                    if (mediaPlayer!=null&&mediaPlayer.isPlaying()){
                        mediaPlayer.seekTo(msg.arg1);
                    }
                    break;
                case 3:
                    playOrPause();
                    break;
            }
        }
    };


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        timer.schedule(timerTask,0,1000);
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                if (playState.equals("1")){//随机播放
                    LogoutT.logout("随机播放");
                    randow();
                }else if(playState.equals("2")){//列表循环
                    LogoutT.logout("列表播放");
                    sequence();
                }else if (playState.equals("3")){//单曲播放
                    LogoutT.logout("单曲播放");
                    single();
                }
            }
        });
    }

    /**
     * 在播放音乐,用广播控制UI界面
     */
    public void isPlay(){
        intent = new Intent();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //  大于等于24即为7.0及以上执行内容
            intent.setComponent(new ComponentName("com.example.music_mediaplayer","com.example.music_mediaplayer.broadcast.MyReceiver"));
        }
        intent.setAction("change_img");
        if (mediaPlayer!=null){
            if (mediaPlayer.isPlaying()){
                intent.putExtra("play_or_pause","playing");
                SharePreferenceTools.getInstance(MyService.this).setString("playing","playing");
                sendBroadcast(intent);
            }else {
                Log.i("001001","5555");
                intent.putExtra("play_or_pause","pause");
                SharePreferenceTools.getInstance(MyService.this).setString("playing","pause");
                sendBroadcast(intent);
            }
        }
    }


    /**
     * 判断当前音乐是否在播放
     * @return
     */
    public static boolean isPlaying(){
        if (mediaPlayer!=null&&mediaPlayer.isPlaying()){
            return true;
        }else {
            return false;
        }
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String url = intent.getStringExtra("url");
        msg = intent.getStringExtra("msg");
        String songName = intent.getStringExtra("songName");
        String songArtist = intent.getStringExtra("songArtist");
        String songPhoto = intent.getStringExtra("songPhoto");
        if (!songName.equals("")){
            SharePreferenceTools.getInstance(MyService.this).setString("songName",songName);
        }
        if (!songArtist.equals("")){
            SharePreferenceTools.getInstance(MyService.this).setString("songArtist",songArtist);
        }
        if (!songPhoto.equals("")){
            SharePreferenceTools.getInstance(MyService.this).setString("songPhoto",songPhoto);
        }
        songLrc = intent.getStringExtra("songLrc");
        if (!url.equals("")){
            intent = new Intent();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                //  大于等于24即为7.0及以上执行内容
                intent.setComponent(new ComponentName("com.example.music_mediaplayer","com.example.music_mediaplayer.broadcast.MyReceiver"));
            }
            intent.setAction("change_name_artist_photo");
            /**
             * 传递歌曲的名字和歌手的名字
             */
            for (int i = 0;i<GlobalVariable.LocationSongList.size();i++){
                if (GlobalVariable.LocationSongList.get(i).getSongPath().equals(url)){
                    number = i;
                    intent.putExtra("song_name",GlobalVariable.LocationSongList.get(i).getSongName());
                    intent.putExtra("song_artist",GlobalVariable.LocationSongList.get(i).getSongArtist());
                    intent.putExtra("song_photo",GlobalVariable.LocationSongList.get(i).getSongPhoto());
                    sendBroadcast(intent);
                }
            }
            if (mediaPlayer.isPlaying()){
                mediaPlayer.stop();
            }
            try {
                mediaPlayer.reset();
                mediaPlayer.setDataSource(url);
                intent.putExtra("song_name",songName);
                intent.putExtra("song_artist",songArtist);
                intent.putExtra("song_photo",songPhoto);
                sendBroadcast(intent);
                mediaPlayer.prepare();
                mediaPlayer.start();
                getMusicDuration();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (!msg.equals("")){
            if (msg.equals("music_play_pause")){
                Log.i("zzzzz","000");
                playOrPause();
            }else if (msg.equals("music_last")){
                if (playState.equals("1")){
                    Log.i("zzzzz","111");
                    randow();
                }else if(playState.equals("2")){
                    Log.i("zzzzz","222");
//                    last();
                    sequence();
                }else if (playState.equals("3")){
                    Log.i("zzzzz","333");
//                    last();
                    single();
                }
            }else if (msg.equals("music_next")){
                if (playState.equals("1")){
                    randow();
                }else if(playState.equals("2")){
//                    next();
                    sequence();
                }else if (playState.equals("3")){
//                    next();
                    single();
                }
            }
        }
        isPlay();
        return START_REDELIVER_INTENT;
    }

    /**
     * 获取当前播放歌曲的歌词
     * @return
     */
    public static String getSongLrc(){
        return songLrc;
    }

    /**
     * 获取当前歌曲的序号
     * @return
     */
    public static int getNumber(){
        LogoutT.logout(number+"     number");
        return number;
    }

    /**
     * 获取歌曲的长度
     */
    public void getMusicDuration(){
        if (mediaPlayer != null&&mediaPlayer.isPlaying()){
            duration = mediaPlayer.getDuration();
        }
        intent = new Intent();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //  大于等于24即为7.0及以上执行内容
            intent.setComponent(new ComponentName("com.example.music_mediaplayer","com.example.music_mediaplayer.broadcast.MyReceiver"));
        }
        intent.setAction("seekBar");
        intent.putExtra("duration",duration);
        sendBroadcast(intent);
    }



    /**
     * 获取当前播放的长度
     */
    public void getMusicCurrentPosition(){
        if (mediaPlayer != null&&mediaPlayer.isPlaying()){
            currentTime = mediaPlayer.getCurrentPosition();
            duration = mediaPlayer.getDuration();
            GlobalVariable.duration = duration;
        }
        intent = new Intent();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //  大于等于24即为7.0及以上执行内容
            intent.setComponent(new ComponentName("com.example.music_mediaplayer","com.example.music_mediaplayer.broadcast.MyReceiver"));
        }
        intent.setAction("seekBar");
        intent.putExtra("currentTime",currentTime);
        intent.putExtra("duration",duration);
        sendBroadcast(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
        timerTask.cancel();
        timer.cancel();
    }


    /**
     * 单曲循环
     */
    public void single(){
        current++;
        current--;
        play(current);
    }

    /**
     * 播放音乐
     * @param current
     */
    public void play(int current){
        Log.i("ooo111","33333333");
            try {
                mediaPlayer.reset();
                mediaPlayer.setDataSource(GlobalVariable.LocationSongList.get(current).getSongPath());
                mediaPlayer.prepare();
                mediaPlayer.start();
                intent = new Intent();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    //  大于等于24即为7.0及以上执行内容
                    intent.setComponent(new ComponentName("com.example.music_mediaplayer","com.example.music_mediaplayer.broadcast.MyReceiver"));
                }
                intent.setAction("change_name_artist_photo");
                intent.putExtra("song_name",GlobalVariable.LocationSongList.get(current).getSongName());
                intent.putExtra("song_artist",GlobalVariable.LocationSongList.get(current).getSongArtist());
                intent.putExtra("song_photo",GlobalVariable.LocationSongList.get(current).getSongPhoto());
                SharePreferenceTools.getInstance(MyService.this).setString("songName",GlobalVariable.LocationSongList.get(current).getSongName());
                SharePreferenceTools.getInstance(MyService.this).setString("songArtist",GlobalVariable.LocationSongList.get(current).getSongArtist());
                SharePreferenceTools.getInstance(MyService.this).setString("songPhoto",GlobalVariable.LocationSongList.get(current).getSongPhoto());
                sendBroadcast(intent);
                Log.i("ooo111","2222222");
                songLrc = GlobalVariable.LocationSongList.get(getNumber()).getSongLyric();
                GlobalVariable.duration = mediaPlayer.getDuration();
                MyObservable.getInstance().notifyChangeView(getNumber());
            } catch (IOException e) {
                e.printStackTrace();
            }
    }


    /**
     * 随机播放
     */
    public void randow(){
        current = new Random().nextInt(GlobalVariable.LocationSongList.size()-1);
        LogoutT.logout(current+"    pppppp");
        Log.i("zzzzz","555");
        number = current;
        play(current);
    }

    /**
     * 列表播放
     */
    public void sequence(){
        if (msg.equals("music_next")){
            current++;
        }else if(msg.equals("music_last")){
            current--;
        }
        if (current>=GlobalVariable.LocationSongList.size()){
            current = 0;
        }
        number = current;
        play(current);
    }

    /**
     * 暂停与播放
     */
    public static void playOrPause(){
        if (mediaPlayer.isPlaying()&&mediaPlayer!=null){
            mediaPlayer.pause();
        }else{
            mediaPlayer.start();
        }
    }

    /**
     * 下一首
     */
    public void next(){
        current++;
        number = current;
        if (current>=GlobalVariable.LocationSongList.size()){
            current = 0;
        }
        play(current);
//        if (mediaPlayer.isPlaying()&&mediaPlayer!=null){
//            mediaPlayer.reset();
//            try {
//                mediaPlayer.setDataSource(GlobalVariable.LocationSongList.get(current).getSongPath());
//                mediaPlayer.prepare();
//                mediaPlayer.start();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
    }

    /**
     * 上一首
     */
    public void last(){
        current--;
        number = current;
        if (current<=0){
            current = GlobalVariable.LocationSongList.size();
        }
//        if (mediaPlayer.isPlaying()&&mediaPlayer!=null){
//            mediaPlayer.reset();
//            try {
//                mediaPlayer.setDataSource(GlobalVariable.LocationSongList.get(current).getSongPath());
//                mediaPlayer.prepare();
//                mediaPlayer.start();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
        play(current);
    }


}
